package zust.study.thread;

import static zust.study.thread.DeadLockDemo.str1;
import static zust.study.thread.DeadLockDemo.str2;

public class DeadLockDemo {

    static String str1 = "obj1";
    static String str2 = "obj2";

    public static void main(String[] args) {
        Thread thread1 = new Thread(new ThreadDemo1());
        Thread thread2 = new Thread(new ThreadDemo2());
        thread1.start();
        thread2.start();
    }

}

class ThreadDemo1 implements Runnable {

    @Override
    public void run() {
        try {
            System.out.println("into demo1");
            while (true) {
                synchronized (DeadLockDemo.str1) {
                    System.out.println("in demo1 :" + DeadLockDemo.str1);
                    Thread.sleep(3000);
                    synchronized (DeadLockDemo.str2) {
                        System.out.println("in demo1 :" + DeadLockDemo.str2);
                    }
                }
            }
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
    }
}

class ThreadDemo2 implements Runnable {

    @Override
    public void run() {
        try {
            System.out.println("into demo2");
            while (true) {
                synchronized (DeadLockDemo.str2) {
                    System.out.println("in demo2 :" + DeadLockDemo.str1);
                    Thread.sleep(3000);
                    synchronized (DeadLockDemo.str1) {
                        System.out.println("in demo2 :" + DeadLockDemo.str2);
                    }
                }
            }
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
    }
}
